package cn.lingyangwl.framework.log;

import cn.lingyangwl.framework.tool.core.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONType;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 操作日志数据
 * {@code @JsonInclude(JsonInclude.Include.NON_EMPTY) }属性为 空（""） 或者为 NULL 都不序列化
 *
 * @author shenguangyang
 */
@Getter
@Setter
@Builder
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JSONType(orders = {"status", "costTime", "ip", "url", "httpMethod", "reqData", "respData"})
public class WebLogInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 请求方式, get / post等方式
     */
    private String httpMethod;

    /**
     * 请求url
     */
    private String url;

    /**
     * 操作地址
     */
    private String ip;

    /**
     * 请求参数
     */
    private String reqData;

    /**
     * 返回参数
     */
    private String respData;

    /**
     * 操作状态 ok/fail
     */
    private String status;

    /**
     * 错误消息
     */
    private String errorMsg;

    /**
     * 耗时单位是ms
     */
    private Long costTime;

    public void printfLog() {
        if (StringUtils.isNotEmpty(reqData) && reqData.length() > 2000) {
            reqData = reqData.substring(0, 2000) + " ......";
        }
        if (StringUtils.isNotEmpty(respData) && respData.length() > 2000) {
            respData = respData.substring(0, 2000) + " ......";
        }
        if (StringUtils.isNotEmpty(errorMsg) && errorMsg.length() > 1000) {
            errorMsg = errorMsg.substring(0, 1000) + " ......";
        }
        log.info("request-{}", JSON.toJSONString(this));
    }
}
